﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using Model;

namespace TanHungLong
{
    public partial class FrmThuChiThuQuy : DevExpress.XtraEditors.XtraForm
    {
        #region variant
        private FormStatus formStatus = FormStatus.View;
        private bool allowCloseForm = true;
        private ThuChiThuQuyBOCollection thuChiThuQuyBOCollection = null;

        private KhachHangBOList khachHangBOList = null;
        private NhanVienBOList nhanVienBOList = null;

        private string COLUMN_FIRST = "SoTien";
        private string COLUMN_SECOND = "NgayLapPhieu";
        private int LoaiPhieu = 0;
        #endregion variant

        //=====================================
        #region form
        public FrmThuChiThuQuy(int LoaiPhieu)
        {
            InitializeComponent();
            this.KeyPreview = true;

            this.LoaiPhieu = LoaiPhieu;
            Session.ThuChiThuQuy_LoaiPhieu = LoaiPhieu;

            this.Text = (LoaiPhieu == 1 ? "Thu nội bộ" : "Chi nội bộ");
            this.lblText.Text = (LoaiPhieu == 1 ? "THU NỘI BỘ" : "CHI NỘI BỘ");
            this.grpThongTinPhieu.Text = "THÔNG TIN PHIẾU " + (LoaiPhieu == 1 ? "THU" : "CHI");
            this.lblMauSo.Text = "Mẫu số: 0" + (LoaiPhieu == 1 ? "1" : "2") + " - TT";
            this.lblLoaiPhieu.Text = "PHIẾU " + (LoaiPhieu == 1 ? "THU" : "CHI");
            this.chkLaKhachHang.Text = "Họ và tên người " + (LoaiPhieu == 1 ? "nộp" : "nhận") + " tiền:";
            this.lblLyDo.Text = "Lý do " + (LoaiPhieu == 1 ? "nộp" : "chi") + ":";

            this.Load += new EventHandler(FrmThuChiThuQuy_Load);
            this.Shown += new EventHandler(FrmThuChiThuQuy_Shown);
            this.FormClosing += new FormClosingEventHandler(FrmThuChiThuQuy_FormClosing);
            this.Activated += new EventHandler(FrmThuChiThuQuy_Activated);
            this.KeyDown += new KeyEventHandler(FrmThuChiThuQuy_KeyDown);

            this.btnPrint.ArrowButtonClick += new EventHandler(btnPrint_ArrowButtonClick);
            this.btnPrint.Click += new EventHandler(btnIn1Phieu_Click);
            this.btnIn1Phieu.Click += new EventHandler(btnIn1Phieu_Click);
            this.btnInThang.Click += new EventHandler(btnInThang_Click);
            this.btnRefresh.Click += new EventHandler(btnRefresh_Click);
            this.btnEdit.Click += new EventHandler(btnEdit_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnCancel.Click += new EventHandler(btnCancel_Click);
            this.btnClose.Click += new EventHandler(btnClose_Click);

            this.grdViewThuChi.RowCellStyle += new RowCellStyleEventHandler(grdViewThuChi_RowCellStyle);
            this.grdViewThuChi.ShowingEditor += new CancelEventHandler(grdViewThuChi_ShowingEditor);
        }

        private void FrmThuChiThuQuy_Shown(object sender, EventArgs e)
        {
            this.gridViewDKB.Focus();
        }

        private void FrmThuChiThuQuy_KeyDown(object sender, KeyEventArgs e)
        {
            if (this.btnClose.Visible && ((e.KeyCode == Keys.Q && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F10)))
                this.Close();
            else
                if (this.btnRefresh.Visible && ((e.KeyCode == Keys.R && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F5)))
                    RefreshData();
                else
                    if (this.btnSave.Visible && ((e.KeyCode == Keys.S && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F6)))
                        Save();
                    else
                        if (this.btnPrint.Visible && ((e.KeyCode == Keys.P && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F7)))
                            In1Phieu();
                        else
                            if (this.btnEdit.Visible && ((e.KeyCode == Keys.E && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F2)))
                                Edit();
                            else
                                if (this.btnCancel.Visible && ((e.KeyCode == Keys.H && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F12)))
                                    Cancel();
                                else
                                    if ((e.KeyCode == Keys.F && Control.ModifierKeys == Keys.Control) || (e.KeyCode == Keys.F3))
                                        this.numNam.Focus();
        }

        private void FrmThuChiThuQuy_Load(object sender, EventArgs e)
        {
            this.lblDonVi.Text = Session.TenDonVi;
            this.numNam.Value = DateTime.Now.Year;

            MyStyle.SetGridStyle(this.gridViewDKB, false);
            Utility.InitControl(this.lookUpKhachHangID);
            Utility.InitControl(this.lookUpNo, "StrSoHieu", "StrSoHieu");
            Utility.InitControl(this.lookUpCo, "StrSoHieu", "StrSoHieu");
            Utility.InitControl(this.lookUpGiamDocID);
            Utility.InitControl(this.lookUpKeToanTruongID);
            Utility.InitControl(this.lookUpNguoiLapPhieuID);
            Utility.InitControl(this.lookUpThuQuyID);

            RefreshData();
            SetFormStatus(this.formStatus);

            this.gridViewDKB.FocusedRowChanged += new FocusedRowChangedEventHandler(gridViewDKB_FocusedRowChanged);
            this.grdViewThuChi.FocusedRowChanged += new FocusedRowChangedEventHandler(grdViewThuChi_FocusedRowChanged);
            this.numNam.ValueChanged += new EventHandler(numNam_ValueChanged);
            this.chkLaKhachHang.CheckedChanged += new EventHandler(chkLaKhachHang_CheckedChanged);
            this.lookUpKhachHangID.EditValueChanged += new EventHandler(lookUpKhachHangID_EditValueChanged);
        }

        private void FrmThuChiThuQuy_Activated(object sender, EventArgs e)
        {
            Session.ThuChiThuQuy_LoaiPhieu = this.LoaiPhieu;
        }

        private void FrmThuChiThuQuy_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.allowCloseForm == false)
                e.Cancel = true;
        }
        #endregion form

        //=====================================
        #region control
        private void numNam_ValueChanged(object sender, EventArgs e)
        {
            FilterNam();
        }

        private void chkLaKhachHang_CheckedChanged(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.Edit)
            {
                this.lookUpKhachHangID.Visible = this.chkLaKhachHang.Checked;
                this.txtHoTen.Visible = !this.chkLaKhachHang.Checked;
            }
        }

        private void lookUpKhachHangID_EditValueChanged(object sender, EventArgs e)
        {
            if (this.formStatus == FormStatus.Edit)
                if (this.chkLaKhachHang.Checked)
                {
                    int? KhachHangID = StaticUtil.GetRealInt(this.lookUpKhachHangID.EditValue);
                    string HoTen = "";
                    if (KhachHangID != null)
                        if (this.khachHangBOList.ContainsKey(KhachHangID.Value))
                            HoTen = this.khachHangBOList.Value(KhachHangID.Value);

                    this.grdViewThuChi.SetFocusedRowCellValue("KhachHangID", KhachHangID);
                    this.grdViewThuChi.SetFocusedRowCellValue("HoTen", HoTen);
                }
        }
        #endregion control

        //=====================================
        #region button
        private void btnPrint_ArrowButtonClick(object sender, EventArgs e)
        {
            this.contextMenuStrip1.Show(this.pnFooter, new Point(this.btnPrint.Location.X, this.btnPrint.Location.Y - 80));
        }

        private void btnInThang_Click(object sender, EventArgs e)
        {
            InThang();
        }

        private void btnIn1Phieu_Click(object sender, EventArgs e)
        {
            In1Phieu();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            Edit();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion button

        //=====================================
        #region grid
        private void grdViewThuChi_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            int? KhachHangID = StaticUtil.GetRealInt(this.grdViewThuChi.GetFocusedRowCellValue("KhachHangID"));
            this.lookUpKhachHangID.EditValue = KhachHangID;
        }

        private void gridViewDKB_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            FilterDotKhaiBao();
        }

        private void grdViewThuChi_ShowingEditor(object sender, CancelEventArgs e)
        {
            bool del = StaticUtil.GetBool(this.grdViewThuChi.GetFocusedRowCellValue("DELE"));
            string fieldName = this.grdViewThuChi.FocusedColumn.FieldName;

            if (del && fieldName != "DELE")
                e.Cancel = true;
            else
                if (fieldName == "DELE" && this.grdViewThuChi.FocusedRowHandle == GridControl.NewItemRowHandle)
                    e.Cancel = true;
        }

        private void grdViewThuChi_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            bool del = StaticUtil.GetBool(this.grdViewThuChi.GetRowCellValue(e.RowHandle, "DELE"));

            if (del)
            {
                e.Appearance.Font = MyStyle.DELETE_FONT;
                e.Appearance.ForeColor = MyStyle.DELETE_COLOR;
            }
        }
        #endregion grid

        //=====================================
        #region function
        private void FilterNam()
        {
            if (this.formStatus == FormStatus.View)
            {
                int nam = decimal.ToInt32(this.numNam.Value);
                DotKhaiBaoBOCollection dotKhaiBaoBOCollection = DotKhaiBaoBOCollection.NewDotKhaiBaoBOCollection();
                int i = 0;
                int length = 12;
                for (i = 1; i <= length; i++)
                {
                    DotKhaiBaoBO dotKhaiBaoBO = DotKhaiBaoBOCollection.NewDotKhaiBaoBO();
                    dotKhaiBaoBO.STT0 = i;
                    dotKhaiBaoBO.Ten = "Tháng " + i.ToString() + "/" + nam.ToString();
                    dotKhaiBaoBOCollection.Add(dotKhaiBaoBO);
                }

                this.bdSourceDKB.DataSource = dotKhaiBaoBOCollection;
                this.gridViewDKB.CheckLoaded();

                if (nam == DateTime.Now.Year)
                    this.gridViewDKB.FocusedRowHandle = DateTime.Now.Month - 1;

                string where = "LoaiPhieu=" + Session.ThuChiThuQuy_LoaiPhieu.Value.ToString();
                where += " AND NgayKyNhan>=CONVERT(datetime,'" + nam + "-01-01 00:00:00',120)";
                where += " AND NgayKyNhan<CONVERT(datetime,'" + (nam + 1) + "-01-01 00:00:00',120)";

                this.thuChiThuQuyBOCollection = ThuChiThuQuyBOCollection.GetThuChiThuQuyBOCollection(where, "NgayKyNhan", "DESC");
                this.bdSourceThuChi.DataSource = this.thuChiThuQuyBOCollection.Clone();

                FilterDotKhaiBao();
            }
        }

        private void FilterDotKhaiBao()
        {
            if (this.formStatus == FormStatus.View)
            {
                int nam = decimal.ToInt32(this.numNam.Value);
                int thang = StaticUtil.GetInt(this.gridViewDKB.GetFocusedRowCellValue("STT0"), 1);

                this.grdViewThuChi.ActiveFilterString = "Thang=" + thang + " AND Nam=" + nam;
                this.grdViewThuChi.CheckLoaded();
                SetSttThuChi();

                Session.ThuChiThuQuy_DotKhaiBao = new DateTime(nam, thang, (nam == DateTime.Now.Year ? DateTime.Now.Day : 1), DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second, DateTime.Now.Millisecond);

                grdViewThuChi_FocusedRowChanged(null, null);
            }
        }

        private void RefreshData()
        {
            int i = 0;
            int length = 0;

            PhongBanBOList phongBanBOList = PhongBanBOList.GetPhongBanBOList();
            this.cmbBoPhan.Properties.Items.Clear();
            length = phongBanBOList.Count;
            for (i = 0; i < length; i++)
                this.cmbBoPhan.Properties.Items.Add(phongBanBOList[i].Value);


            //khach hang bo list
            this.khachHangBOList = KhachHangBOList.GetKhachHangBOList();
            Utility.SetData(this.lookUpKhachHangID, this.khachHangBOList, this.khachHangBOList.Count);


            SoHieuTaiKhoanBOCollection soHieuTaiKhoanBOCollection = SoHieuTaiKhoanBOCollection.GetSoHieuTaiKhoanBOCollection();
            soHieuTaiKhoanBOCollection.Sort();
            Utility.SetData(this.lookUpNo, soHieuTaiKhoanBOCollection, soHieuTaiKhoanBOCollection.Count);
            Utility.SetData(this.lookUpCo, soHieuTaiKhoanBOCollection, soHieuTaiKhoanBOCollection.Count);

            //nhan vien
            this.nhanVienBOList = NhanVienBOList.GetNhanVienBOList();
            Utility.SetData(this.lookUpGiamDocID, this.nhanVienBOList, this.nhanVienBOList.Count);
            Utility.SetData(this.lookUpKeToanTruongID, this.nhanVienBOList, this.nhanVienBOList.Count);
            Utility.SetData(this.lookUpNguoiLapPhieuID, this.nhanVienBOList, this.nhanVienBOList.Count);
            Utility.SetData(this.lookUpThuQuyID, this.nhanVienBOList, this.nhanVienBOList.Count);

            FilterNam();
        }

        private void Edit()
        {
            this.formStatus = FormStatus.Edit;
            SetFormStatus(this.formStatus);
            Session.CloseIndex++;
        }

        private void Save()
        {
            string oldColumn = this.grdViewThuChi.FocusedColumn.FieldName;
            string newColumn = (oldColumn == this.COLUMN_FIRST ? this.COLUMN_SECOND : this.COLUMN_FIRST);
            this.grdViewThuChi.FocusedColumn = this.grdViewThuChi.Columns[newColumn];

            this.bdSourceThuChi.EndEdit();

            this.thuChiThuQuyBOCollection = (ThuChiThuQuyBOCollection)this.bdSourceThuChi.DataSource;
            this.thuChiThuQuyBOCollection = this.thuChiThuQuyBOCollection.Save();
            this.bdSourceThuChi.DataSource = this.thuChiThuQuyBOCollection.Clone();

            this.grdViewThuChi.FocusedColumn = this.grdViewThuChi.Columns[oldColumn];

            this.formStatus = FormStatus.View;
            SetFormStatus(this.formStatus);
            Session.CloseIndex--;

            this.grdViewThuChi.CheckLoaded();
            SetSttThuChi();
            grdViewThuChi_FocusedRowChanged(null, null);
        }

        private void Cancel()
        {
            this.formStatus = FormStatus.View;
            SetFormStatus(this.formStatus);
            Session.CloseIndex--;

            this.bdSourceThuChi.DataSource = this.thuChiThuQuyBOCollection.Clone();

            this.grdViewThuChi.CheckLoaded();
            SetSttThuChi();
            grdViewThuChi_FocusedRowChanged(null, null);
        }

        private void In1Phieu()
        {
            //lay data
            int? ThuChiID = StaticUtil.GetRealInt(this.grdViewThuChi.GetFocusedRowCellValue("ThuChiThuQuyID"));
            if (ThuChiID != null)
            {
                ThuChiThuQuyBO thuChiBO = this.thuChiThuQuyBOCollection.GetThuChiThuQuyBO(ThuChiID.Value);

                if (Session.ThuChi_LoaiPhieu.Value == 1)
                {
                    //goi phieu thu
                    Report.rpPhieuThu report = new TanHungLong.Report.rpPhieuThu(thuChiBO, this.nhanVienBOList);
                    report.ShowPreviewDialog();
                }
                else
                {
                    //goi phieu chi
                    Report.rpPhieuChi report = new TanHungLong.Report.rpPhieuChi(thuChiBO, this.nhanVienBOList);
                    report.ShowPreviewDialog();
                }
            }
        }

        private void InThang()
        {
            //lay data
            ThuChiThuQuyBOCollection tmpThuChiBOCollection = ThuChiThuQuyBOCollection.NewThuChiThuQuyBOCollection();
            int index = 0;
            int? ThuChiID = null;
            int length = this.grdViewThuChi.RowCount;
            for (int i = 0; i < length; i++)
            {
                index = this.grdViewThuChi.GetVisibleRowHandle(i);
                if (index >= 0)
                {
                    ThuChiID = StaticUtil.GetRealInt(this.grdViewThuChi.GetRowCellValue(index, "ThuChiThuQuyID"));
                    if (ThuChiID != null)
                    {
                        ThuChiThuQuyBO thuChiBO = this.thuChiThuQuyBOCollection.GetThuChiThuQuyBO(ThuChiID.Value);
                        tmpThuChiBOCollection.Add(thuChiBO);
                    }
                }
            }

            if (tmpThuChiBOCollection.Count > 0)
            {
                Report.rpDanhSachThuChi report = new TanHungLong.Report.rpDanhSachThuChi(Session.ThuChiThuQuy_LoaiPhieu.Value, tmpThuChiBOCollection, this.nhanVienBOList);
                report.ShowPreviewDialog();
            }
        }

        private void SetFormStatus(FormStatus formStatus)
        {
            bool edit = (formStatus != FormStatus.View);
            this.allowCloseForm = !edit;

            MyStyle.SetGridStyle(this.grdViewThuChi, edit);
            Utility.SetControlReadOnly(this.grpThongTinPhieu, !edit);

            this.numNam.Enabled = !edit;
            this.grdControlDKB.Enabled = !edit;

            this.btnEdit.Visible = !edit;
            this.btnClose.Visible = !edit;
            this.btnRefresh.Visible = !edit;

            this.btnSave.Visible = edit;
            this.btnCancel.Visible = edit;

            this.colDELE_ThuChi.Visible = edit;
            foreach (GridColumn col in this.grdViewThuChi.Columns)
            {
                if (col.Visible)
                    col.OptionsColumn.AllowEdit = edit;
            }

            this.grdViewThuChi.OptionsView.NewItemRowPosition = (edit ? NewItemRowPosition.Bottom : NewItemRowPosition.None);
            this.grdViewThuChi.Focus();

            if (edit)
            {
                string focusColumn = this.grdViewThuChi.FocusedColumn.FieldName;

                if (string.IsNullOrEmpty(focusColumn))
                    focusColumn = this.COLUMN_FIRST;
                else
                    if (focusColumn == "DELE")
                        focusColumn = this.COLUMN_FIRST;

                if (this.grdViewThuChi.RowCount == 1)
                    this.grdViewThuChi.FocusedRowHandle = int.MinValue + 1;

                this.grdViewThuChi.FocusedColumn = this.grdViewThuChi.Columns[focusColumn];
                this.grdViewThuChi.ShowEditor();

                //
                this.lookUpKhachHangID.Visible = this.chkLaKhachHang.Checked;
                this.txtHoTen.Visible = !this.chkLaKhachHang.Checked;
            }
            else
            {
                this.lookUpKhachHangID.Visible = false;
                this.txtHoTen.Visible = true;
            }
        }

        private void SetSttThuChi()
        {
            if (this.formStatus == FormStatus.Edit)
                this.bdSourceThuChi.EndEdit();

            int stt = 0;
            int length = this.grdViewThuChi.RowCount;
            int index = 0;
            for (int i = 0; i < length; i++)
            {
                index = this.grdViewThuChi.GetVisibleRowHandle(i);
                if (index >= 0)
                    this.grdViewThuChi.SetRowCellValue(i, "STT0", ++stt);
            }

            ((ThuChiThuQuyBOCollection)this.bdSourceThuChi.DataSource).SttIndex = stt;
        }
        #endregion function
    }
}